<template>
  <div class="right-side crtl-box">
    <main v-cloak
          id="app">
      <div class="cm-container">
        <div class="code_head">
          <span class="title fl">源代码编辑器</span>
          <a class="code_run"
             href="javascript:;"
             @click="runCode">运行</a>
        </div>
        <codemirror :value="codeVal"
                    ref="myEditor"
                    :options="editorOption"></codemirror>
      </div>
    </main>

  </div>
</template>
<style scoped>
  .code-edit {
    height: 100%;
  }
  .right-side {
    position: absolute;
    top: 0px;
    right: 0;
    width: 380px;
    height: 100%;
  }
  .code_head {
    height: 41px;
    line-height: 41px;
    background: #f8f9fa;
    border-top: 1px solid #e5e5e5;
    border-bottom: 1px solid #e5e5e5;
  }
  .code_head .title {
    padding-left: 20px;
  }
  .code_run {
    float: right;
    display: block;
    padding: 0 16px;
    color: #414141;
    outline: 0;
  }
  .code_run:hover {
    color: #0097db;
  }
</style>
<script>
  import { codemirror } from 'vue-codemirror-lite'
  require('codemirror/addon/hint/show-hint.js')
  require('codemirror/addon/hint/show-hint.css')
  require('codemirror/addon/hint/javascript-hint.js')
  require('codemirror/addon/hint/xml-hint.js')
  require('codemirror/addon/hint/html-hint.js')
  require('codemirror/mode/xml/xml.js')
  require('codemirror/mode/javascript/javascript.js')
  require('codemirror/mode/css/css.js')
  require('codemirror/mode/htmlmixed/htmlmixed.js')
  export default {
    data () {
      return {
        codeVal: '',
        //  code: '',
        myEditor: null,
        editorOption: {
          lineNumbers: true,     // 显示行数
          indentUnit: 4,         // 缩进单位为4
          styleActiveLine: true, // 当前行背景高亮
          matchBrackets: true,   // 括号匹配
          mode: 'text/html',     // HMTL混合模式
          lineWrapping: true,    // 自动换行
          extraKeys: { "Ctrl-Space": "autocomplete" }
        }
      }
    },
    props: {
      code: {
        type: String,
        default: ''
      }
    },
    watch: {
      code (curVal, oldVal) {
        if (curVal != oldVal) {
          this.codeVal = curVal;
        }
      }
    },
    mounted () {
      this.codeVal = this.code;
      this.$nextTick(() => {
        this.myEditor = this.$refs['myEditor'].editor
        let editor = document.querySelector('.CodeMirror')
        let height = (document.documentElement ? document.documentElement.clientHeight : document.body.clientHeight) - 42
        editor.style.height = height + 'px';
      })

    },
    methods: {
      runCode () {
        this.$emit('changeHtml', this.myEditor.getValue())
      }
    },
    components: {
      codemirror
    }
  }
</script>

